/******************************************************************
* Description:                                                    *
*        This demo show you how to implement input password       *
*        but do not display anything.                             *
*                                                                 *
******************************************************************/
#include <termios.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>

#define DEL() printf("\033[D \033[D")
#define LEN 256

void cyscanf(char *str, int n);

void cyscanf(char *str, int n)
{
    int hide = 1;
    int len = 0;
    char ch;
    struct termios old_term;
    struct termios cur_term;
    tcgetattr(STDIN_FILENO, &old_term);
    memcpy(&cur_term, &old_term, sizeof(cur_term));
    cur_term.c_lflag &= ~(ICANON|ECHO|ECHOE|ECHOK|ECHONL);
    cur_term.c_cc[VMIN] = 1;
    cur_term.c_cc[VTIME] = 0;
    tcsetattr(STDIN_FILENO, TCSAFLUSH, &cur_term);

    while (1)
    {
        ch = getchar();
        if (ch == '\n') break;
        if (ch == 8 && len > 0)
        {
            // backspace
            len--;
            if(hide == 0) DEL();
            continue;
        }
        if (ch == '\33')
        {
            ch = getchar();
            if (ch == '[')
            {
                ch = getchar();
                switch (ch)
                {
                    case 'A':
                        //printf("\nMOVEUP");
                        break;
                    case 'B':
                        //printf("\nMOVEDOWN");
                        break;
                    case 'C':
                        //printf("\nMOVERIGHT");
                        break;
                    case 'D':
                        //printf("\nMOVELEFT");
                        break;
                }
                continue;
            }
        }
        if (ch > 31 && ch <127 && len < n)
        {
            if(hide == 0) printf("%c", ch);
            str[len++] = ch;
        }
        fflush(stdout);
    }
    tcsetattr(STDIN_FILENO, TCSAFLUSH, &old_term);
    str[len] = '\0';
    printf("\n");
}

int main(int argc, char *argv[])
{
    char buf[LEN];
    printf("Please Enter Passwd:");
    cyscanf(buf, LEN);
    printf("Passwd: %s\n", buf);

    return 0;
}
